package utils;

import java.nio.ByteBuffer;

/**
 * Utility functions to convert data into differing types.
 * To byte array functions not needed because writeShort() 
 * converts to network byte order.
 * 
 * @author lilywong
 *
 */
public class Conversions {

	 /**
	  * Convert a short to a byte array, flips bytes for network order.
	  * @param i
	  * @return byte array
	  */
	public static byte[] intToBytes( int i ) {
		byte[] b = new byte[2];
		b[0] = (byte) ((i >> 8) & 0xFF); 
		b[1] = (byte) (i & 0xFF);
		return b;
	}
	
	/**
	 * Convert byte array to a short, flips bytes for host order.
	 * @param b
	 * @return short
	 */
	public static int bytesToInt( byte[] b ) {
		return (int) (((b[0] & 0xFF) << 8) + (b[1] & 0xFF));
	}
	
	public static byte[] int4ToBytes( int l ) {
		return ByteBuffer.allocate(4).putInt(l).array();
		/*
		byte[] b = new byte[8];
		for (int i = 0; i < size; ++i) {
  			b[i] = (byte) (l >> (size - i - 1 << 3));
		}
		return b;
		*/
	}
	
	public static int bytesToInt4( byte[] b ) {
		int value = 0;
		for (int i = 0; i < b.length; i++)
		{
		   value = (value << 8) + (b[i] & 0xFF);
		}
		return value;
	}
	
	public static int booleanToInt( boolean b ) {
		if ( b ) return 1;
		return 0;
	}
	

	public static boolean intToBoolean( int i ) {
		if ( i == 1 ) return true;
		return false;
	}
	
	public static int booleanToShort( boolean b ) {
		if ( b ) return (short) 1;
		return (short) 0;
	}
	
}
